const axios = require("axios");
const APP_ID = "2ece4be7";
const APP_PWD = "CquduBxLgqvMukAqedsH:eOrMSCcztBHjuBWnAHoY";
const API_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
const headers = {
  Authorization: `Bearer ${APP_PWD}`,
  "X-Appid": APP_ID,
  "Content-Type": "application/json",
};
const data = {
    model: "generalv3.5", 
    messages: [
      {
        role: "user",
        content: "什么是JavaScript",
      },
    ],
    stream:true
  };
const OpenAiRequest = async (socket,content) => {
  let ResponseResult = "";
  data.messages[0].content = content
  try {
    const response = await axios.post(API_URL, data, {
      headers,
      responseType: "stream",
    });
    // 逐块处理流数据
      response.data.on("data", (chunk) => {
      ResponseResult += chunk.toString("utf-8").replace("data:", "");
      try {
        const parsedChunk = JSON.parse(ResponseResult);
        const content = parsedChunk.choices[0]?.delta?.content
        socket.emit("receiveMessage", content);
        ResponseResult = ""; // 清空字符串以准备接收下一个数据块
      } catch (err) {
        console.error("当前数据块未能解析:", err.message);
      }
    });
    response.data.on("end", () => {
      socket.emit("dataEnd", true);
    });

    response.data.on("error", (err) => {
      console.error("流接收错误:", err);
      socket.emit("error", "流接收错误");
    });
  } catch (error) {
    console.error("请求发生错误:", error.message);
    socket.emit("error", "请求发生错误");
  }
};

module.exports = OpenAiRequest
